package com.hzh.cusviewdemo.Adapter;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载更多的适配器基类
 *
 */
public abstract class BaseLoadMoreDataAdapter<T> extends BaseRecyclerAdapter<T> {

    private int mCount; // 加载数量 默认20
    private final int mInitCount;

    public BaseLoadMoreDataAdapter(Context context) {
        this(context, new ArrayList<>(), 20);
    }

    public BaseLoadMoreDataAdapter(Context context, List<T> dataList) {
        this(context, dataList, 20);
    }

    public BaseLoadMoreDataAdapter(Context context, List<T> dataList, int count) {
        super(dataList, context);
        this.mCount = count;
        mInitCount = count;
    }

    @Override
    public int getItemCount() {
        if (mCount == -1) {
            // -1时直接加载全部
            return getSize();
        }
        if (getSize() <= 20) {
            return getSize();
        } else {
            return mCount;
        }
    }

    public void setDataAndNotifyUpdate(List<T> dataList) {
        setData(dataList);
    }

    public int getCount() {
        return mCount;
    }

    public void loadMore() {
        if (mCount == -1) {
            return;
        }
        final int positionStart = mCount;
        if (getSize() <= 20) {
            return;
        }
        if (mCount == getSize()) {
            // 全部加载OK
            return;
        }
        int loadNum = Math.min(getSize() - mCount, 20);
        mCount += loadNum;
        notifyItemRangeInserted(positionStart, loadNum);
    }

    @Override
    public void delete(int pos) {
        mCount--;
        super.delete(pos);
    }

    @Override
    public void add(int pos, T item) {
        mCount++;
        super.add(pos, item);
    }

    @Override
    public void addAll(int position, List<T> items) {
        if (items == null) {
            return;
        }
        if (mData.size() == 0) {
            mCount = items.size();
        } else {
            mCount += items.size();
        }
        // Log.e(Config.TAG, "更新后数量：" + mCount);
        super.addAll(position, items);
    }

    @Override
    public void setData(List<T> items) {
        mCount = mInitCount;
        super.setData(items);
    }

    @Override
    public void clear() {
        mCount = mInitCount;
        super.clear();
    }
}